package com.clusterswisdom.horn.api.tmall.action.alipay;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.lang3.time.DateFormatUtils;

import com.alibaba.fastjson.JSONObject;
import com.clusterswisdom.horn.api.ioc.HornAction;
import com.clusterswisdom.horn.api.ioc.HornResponse;
import com.clusterswisdom.horn.api.ioc.api.ApiConfig;
import com.clusterswisdom.horn.api.tmall.TmallInstance;
import com.clusterswisdom.horn.api.tmall.action.AbstractTmallAction;
import com.clusterswisdom.horn.api.tmall.action.bill.data.BillFee;
import com.clusterswisdom.horn.api.tmall.action.bill.data.ChannelOrderBill;
import com.clusterswisdom.horn.api.tmall.action.bill.data.ChannelOrderBillItem;
import com.taobao.api.domain.TradeRecord;
import com.taobao.api.response.AlipayUserTradeSearchResponse;

public class GetBillsByDateAction extends AbstractTmallAction implements HornAction{
	public static final String CHANNEL_NAME = "天猫";
	
	@Override
	public HornResponse execute(ApiConfig config, JSONObject param)
			throws Exception {
		ChannelOrderBill bill = getBills(param);
		
		return new HornResponse(true, bill);
	}
	
	private ChannelOrderBill getBills(JSONObject param) throws Exception{
		ChannelOrderBill bill = new ChannelOrderBill();
		bill.setChannel(CHANNEL_NAME);
		bill.setBillDateStr(getBillDateStr(param));
		bill.setBillSpanStr(getBillSpanStr(param));
		bill.setOrderList(getOrderList(param));
		return bill;
	}
	
	protected String getBillDateStr(JSONObject param) {
		Calendar begin = getBeginDate(param);
		
		StringBuilder builder = new StringBuilder();
		builder.append(begin.get(Calendar.YEAR));
		builder.append("-");
		builder.append((begin.get(Calendar.MONTH) + 1));
		builder.append("月");
		return builder.toString();
	}
	
	protected String getBillSpanStr(JSONObject param) {
		Calendar begin = getBeginDate(param);
		Calendar end = getEndDate(param);
		
		StringBuilder builder = new StringBuilder();
		builder.append(DateFormatUtils.format(begin, "yyyy-MM-dd"));
		builder.append("至");
		builder.append(DateFormatUtils.format(end, "yyyy-MM-dd"));
		
		return builder.toString();
	}
	
	private Calendar getBeginDate(JSONObject param) {
		Calendar calendar = param == null ? null : GregorianCalendar.getInstance();
		Date begin = param.getDate("startTime");
		if (begin != null) {
			calendar.setTime(begin);
			
		} else {
			calendar.set(Calendar.DAY_OF_MONTH, 28);
			calendar.add(Calendar.MONTH, -1);
			
		}
		
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		
		return calendar;
	}
	
	private Calendar getEndDate(JSONObject param) {
		Date end = param == null ? null : param.getDate("lastTime");
		Calendar calendar = GregorianCalendar.getInstance();
		if (end != null) {
			calendar.setTime(end);
			
		} else {
			calendar.set(Calendar.DAY_OF_MONTH, 27);
			
		}
		
		calendar.set(Calendar.HOUR_OF_DAY, 23);
		calendar.set(Calendar.MINUTE, 59);
		calendar.set(Calendar.SECOND, 59);
		calendar.set(Calendar.MILLISECOND, 999);
		
		return calendar;
	}
	
	/**
	 * 通过支付宝获取订单列表和其中的费用列表
	 * @param param
	 * @return
	 * @throws Exception
	 */
	private List<ChannelOrderBillItem> getOrderList(JSONObject param) throws Exception{
		List<ChannelOrderBillItem> orderbills =new LinkedList<ChannelOrderBillItem>();
		List<TradeRecord> tradeRecords = getTradeRecords(param);
		//获取订单
		if(tradeRecords == null || tradeRecords.size() == 0){
			return null;
		}
		
		int[] num = new int[tradeRecords.size()];
		int i = 0;
		for(TradeRecord tradeRecord:tradeRecords){	
			if(num[i] == i  && i != 0){
				String orderNo=tradeRecord.getMerchantOrderNo();
				ChannelOrderBillItem item = new ChannelOrderBillItem();
				String orderId = "";
				if(orderNo.contains("T2400P")){
					//订单编号
					orderId = orderNo.substring(5);
					item.setTotalMoney(tradeRecord.getTotalAmount());
					item.setCountMoney(Double.toString(Double.parseDouble(tradeRecord.getTotalAmount())-Double.parseDouble(tradeRecord.getServiceCharge())));
					num[i] = i;
				}
				int j = 0;
				List<BillFee> billFees =new LinkedList<BillFee>(); 
				for(TradeRecord othertradeRecord:tradeRecords){
					BillFee billFee = new BillFee();
					String otherOrderNo =othertradeRecord.getMerchantOrderNo();
					if(!otherOrderNo.contains("T") && otherOrderNo.contains(orderId) ){
						if(otherOrderNo.contains("")){
							billFee.setFeeCode("");
							billFee.setFeeName("");
							billFee.setFeeValue(othertradeRecord.getTotalAmount());
							num[j] = j;
						}
					}
					billFees.add(billFee);
					j++;
				}
				item.setFeeMoney(getFeeMoney(item));
				item.setDifferFee(getDifferFee(item));
				orderbills.add(item);
			}
			i++;
		}
		return orderbills;
	}
	
	private List<TradeRecord> getTradeRecords(JSONObject param) throws Exception{
		List<TradeRecord> tradeRecords = new LinkedList<TradeRecord>();
		int pag_no = 1;
		int total_result = -1;
		do{
			param.put("page_no", pag_no++);
			param.put("order_status", "");
			AlipayUserTradeSearchResponse response=(AlipayUserTradeSearchResponse)TmallInstance.getInstance().executeRequest(param, "alipay", "searchUserTrade");
			if(total_result == -1){
				total_result = Integer.parseInt(response.getTotalResults());
			}
			if(response.getTradeRecords() != null){
				tradeRecords.addAll(response.getTradeRecords());
			}
		}while(tradeRecords.size() < total_result);
		return tradeRecords;
	}
	
	private String getDifferFee(ChannelOrderBillItem item){
		
		return null;
	}
	
	private String getFeeMoney(ChannelOrderBillItem item){
		List<BillFee> billFees = item.getFeeList();
		double feeMoney = 0.00;
		if(billFees != null){
			for(BillFee billFee : billFees){
				if(billFees != null){
					feeMoney += Double.parseDouble(billFee.getFeeValue());
				}
			}
		}
		return Double.toString(feeMoney);
	}
}
